import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_login.dart';
import 'package:gold/http/http.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_utils.dart';

/// @description:
/// @author tangzhentao
/// @created at 21:12 2025/1/1

class PhoneViewmodel extends Viewmodel {
  /// 手机号
  final TextEditingController phoneController = TextEditingController();
  final FocusNode phoneNode = FocusNode();

  /// 密码或验证码
  final TextEditingController codeController = TextEditingController();
  final FocusNode codeNode = FocusNode();

  bool _isNext = false;
  /// 是否下一步
  bool get isNext => _isNext;
  set isNext(bool value) {
    if (_isNext != value) {
      _isNext = value;
      notifyListeners();
    }
  }

  /// 验证码计时器
  Timer? _timer;
  /// 验证码倒计时
  int _codeSecond = 60;
  int get codeSecond => _codeSecond;
  set codeSecond(int value) {
    if (_codeSecond != value) {
      _codeSecond = value;
      notifyListeners();
    }
  }

  /// 是否可点击
  bool _canClick = false;
  bool get canClick => _canClick;

  /// 发送验证码是否可以点击
  bool _canCodeClick = true;
  bool get canCodeClick => _canCodeClick;
  set canCodeClick(bool value) {
    if (_canCodeClick != value) {
      _canCodeClick = value;
      notifyListeners();
    }
  }

  /// 手机号变化
  void phoneChanged(String phone) {
    bool changed = false;
    final codeClick = isPhone(phone);
    if (_canCodeClick != codeClick) { _canCodeClick = codeClick; changed = true; }
    final click = codeClick && codeController.text.isNotEmpty;
    if (_canClick != click) { _canClick = click; changed = true; }
    if (changed) notifyListeners();
  }

  /// 验证码变化
  void codeChanged(String code) {
    final click = (!_isNext || (_isNext && isPhone(phoneController.text))) && code.length == 6;
    if (_canClick != click) {
      _canClick = click;
      notifyListeners();
    }
  }

  /// 发送验证码
  Future sendCode() async {
    hideKeyboard();
    if (_codeSecond != 60) return;
    final result = await Http().request<String>(ApiLogin.sendSmsCode,
        data: {
          'mobile': isNext ? phoneController.text:XfgNav.read<UserProvider>().user.user?.mobile?.toString(),
          'event': isNext ? 'editMobile':'verifyMobile'}, successText: '已发送');
    if (result.success) {
      _startTimer();
    }
  }

  /// 按钮处理
  Future buttonHandle() async {
    hideKeyboard();
    if (isNext) {
      final result = await Http().request<dynamic>(ApiLogin.editMobile,
          data: {'mobile': phoneController.text, 'captcha': codeController.text}, loadingText: '换绑中...', successText: '换绑成功~');
      if (result.success) {
        await XfgNav.read<UserProvider>().updateProfile();
        XfgNav.pop();
      }
    } else {

      final result = await Http().request<dynamic>(ApiLogin.verifyMobile,
          data: {'mobile': XfgNav.read<UserProvider>().user.user?.mobile?.toString(), 'captcha': codeController.text}, loadingText: '验证中...');
      if (result.success) {
        _isNext = true;
        phoneController.text = '';
        codeController.text = '';
        _canClick = false;
        _canCodeClick = false;
        _cancelTimer();
        notifyListeners();
      }
    }
  }

  /// 开启计时器
  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      codeSecond--;
      if (codeSecond == 0) {
        _cancelTimer();
      }
    });
  }

  /// 停止计时器
  void _cancelTimer() {
    codeSecond = 60;
    _timer?.cancel();
    _timer = null;
  }

  @override
  void dispose() {
    phoneController.dispose();
    phoneNode.dispose();
    codeController.dispose();
    codeNode.dispose();
    super.dispose();
  }
}
